import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";
import { TurbStatusExprService } from "../../../../service/turbstatus_expr.service";
// import { TurbStatusService } from "../../../../service/turbstatus.service";
import { CalculateExpression, StationTagMark } from "../../../../entity/calculate-expression.model";
import { CalculateExpressionService } from '../../../../service/calculate-expression.service';
import { StationTag } from "../../../../entity/station-tag.model";
import { StationTagService } from "../../../../service/station-tag.service";

@Component({
  selector: 'app-calculate-expression-edit',
  templateUrl: './calculate-expression-edit.component.html',
  styleUrls: ['./calculate-expression-edit.component.css']
})
export class CalculateExpressionEditComponent extends BladeContainerBase<CalculateExpression> {
  /**
   * 表达式标识
   * 
   * @type {StationTag[]}
   * @memberof CalculateExpressionEditComponent
   */
  original: StationTag[] = [];
  expressionMark: StationTag[] = [];

  marks: StationTagMark[] = [];

  /**
   * 验证结果
   * 
   * @type {boolean}
   * @memberof StausExperEditComponent
   */
  result: Result = {
    code: -1,
    messages: ''
  };
  constructor(
    private fb: FormBuilder,
    private stationTagService: StationTagService,
    private calculateExpressionService: CalculateExpressionService,
    private turbStatusExprService: TurbStatusExprService
  ) {
    super(fb);
  }

  ngOnInit() {
    this.commands = [
      new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
      new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
    ]
    this.stationTagService.getStationTagsList()
      .then(res => {
        if (res) {
          this.marks = [];
          this.original = [...res];
          this.expressionMark = this.original.filter(o => o.farmId === this.currentEntity.farmId);
          this.expressionMark.forEach(o => {
            const mark = {
              stationTagId: o.stationTagId,
              stationTagName: o.stationTagName,
              expressionMark: o.expressionMark,
              value: 1
            };
            this.marks.push(mark);
          });
        };
      })
      .catch(error => this.bladeData.error = error)
      .then(res => this.bladeData.isLoading = false);

    super.ngOnInit();

  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    // return this.hasChange() && !this.hasError();
    return this.result.code == 200 && !this.hasError();
  }
  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return this.hasChange();
  }

  /**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
  createForm() {
    this.formGroup = this.fromBuider.group({
      "result": [this.currentEntity.result, []],
      "categoryName": [this.currentEntity.categoryId, [
        Validators.required,
      ]],
      "expression": [this.currentEntity.expression, [
        Validators.required,
        Validators.maxLength(200),
      ],] //(control: FormControl): any => this.expressionAsnyValidator(control)
    });
  }

  /**
  * 设置表单错误对象
  * 
  * 
  * @memberof BladeContainerBase
  */
  setFormError(): void {
    this.formErrors = {
      'categoryName': '',
      'expression': '',
    };
  }

  /**
 * 设置表单验证信息
 * 
 * 
 * @memberof BladeContainerBase
 */
  setValidationMessages(): void {
    this.validationMessages = {
      'categoryName': {
        'required': '不能为空。',
      },
      'expression': {
        'required': '不能为空。',
        'maxlength': '表达式不能多于20个字符长度。',
        'exist': '表达式已存在',
      }

    };
  }
  expressionAsnyValidator(control: FormControl): any {
    if (!control.value || control.value === this.currentEntity.expression) {
      return Observable.of(null);
    }
    // tslint:disable-next-line:max-line-length
    return this.calculateExpressionService.hasExpression(control.value, this.currentEntity.farmId, this.currentEntity.phaseId, this.currentEntity.categoryId)
      .map(res => res ? { exist: true } : null);
  }

  /**
    * 校验
    * 
    * 
    * @memberof DicKeyEditComponent
    */
  onCheck(): any {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.expression = formValue.expression;
      let str = this.currentEntity.expression;
      let reg = new RegExp("@[A-Z]([0-9]{1,})#", 'g');
      let curstr = str.match(reg) != null ? str.match(reg).join().split(',') : [];
      for (let i = 0; i < this.marks.length; i++) {
        let curValue = this.marks[i].value;
        let curTagStateMark = "@" + this.marks[i].expressionMark + "#";
        for (let j = 0; j < curstr.length; j++) {
          if (curTagStateMark === curstr[j]) {
            str = str.replace(new RegExp("@[A-Z]([0-9]{1,})#", 'g'), function (a) {
              a = curValue.toString();
              return a;
            });
          }
        }

      }
      this.turbStatusExprService.exprCheck(str)
        .then(res => {
          this.result = res;
          (this.parentBlade.bladeContainerInstance).refresh(this.currentEntity);
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }

  }

  saveChange(): any | Promise<any> | Observable<any> {
    // 校验
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      let str = formValue.expression;
      let reg = new RegExp("@[A-Z]([0-9]{1,})#", 'g');
      let curstr = str.match(reg) != null ? str.match(reg).join().split(',') : [];

      for (let i = 0; i < this.marks.length; i++) {
        let curValue = this.marks[i].value;
        let curTagStateMark = "@" + this.marks[i].expressionMark + "#";
        for (let j = 0; j < curstr.length; j++) {
          if (curTagStateMark === curstr[j]) {
            str = str.replace(new RegExp("@[A-Z]([0-9]{1,})#", 'g'), function (a) {
              a = curValue.toString();
              return a;
            })
          }
        }
      }
      this.turbStatusExprService.exprCheck(str)
        .then(res => {
          this.result = res;
          // 保存
          if (this.result.code == 200) {
            if (this.canSaveChange(this.currentBlade)) {
              this.bladeData.isLoading = true;
              let formValue = this.formGroup.value;
              this.currentEntity.expression = formValue.expression;
              let currentExpr = {
                expressionId: this.currentEntity.expressionId,
                expression: this.currentEntity.expression,
                categoryId: this.currentEntity.categoryId,
                farmId: this.currentEntity.farmId,
                phaseId: this.currentEntity.phaseId,
                desc: ''
              }
              if (currentExpr.expressionId) {
                return this.calculateExpressionService.update(currentExpr)
                  .then(res => {
                    if (res) {
                      (this.parentBlade.bladeContainerInstance).refresh(res);
                      this.bladeService.closeBlade(this.currentBlade);
                      return true;
                    }
                  })
                  .catch(error => this.bladeData.error = error)
                  .then(res => this.bladeData.isLoading = false);
              } else {
                return this.calculateExpressionService.create(currentExpr)
                  .then(res => {
                     (this.parentBlade.bladeContainerInstance).refresh(res);
                      this.bladeService.closeBlade(this.currentBlade);
                      return true;
                    // if (res) {
                    //   (this.parentBlade.bladeContainerInstance).refresh(res);
                    //   this.bladeService.closeBlade(this.currentBlade);
                    //   return true;
                    // }
                  })
                  .catch(error => this.bladeData.error = error)
                  .then(res => this.bladeData.isLoading = false);
              }

            }
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }

  }

}

export interface Result {
  code: number;
  messages: string;
}



// WEBPACK FOOTER //
// ./src/app/module/basic/calculate-expression/calculate-expression-edit/calculate-expression-edit.component.ts